<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card class="search-wrapper">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="订单编号">
          <el-input v-model="queryParams.order_no" placeholder="请输入订单编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="卡号">
          <el-input v-model="queryParams.card_no" placeholder="请输入卡号" clearable></el-input>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="待支付" value="pending"></el-option>
            <el-option label="已支付" value="paid"></el-option>
            <el-option label="已完成" value="completed"></el-option>
            <el-option label="已取消" value="cancelled"></el-option>
            <el-option label="已退款" value="refunded"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card class="box-card">
      <el-table
        v-loading="loading"
        :data="orderList"
        border
        style="width: 100%"
      >
        <el-table-column prop="order_no" label="订单编号" width="180"></el-table-column>
        <el-table-column prop="card_no" label="卡号" width="150"></el-table-column>
        <el-table-column prop="contact_name" label="联系人" width="120"></el-table-column>
        <el-table-column prop="contact_phone" label="联系电话" width="120"></el-table-column>
        <el-table-column prop="total_amount" label="订单金额" width="120">
          <template #default="scope">
            ¥{{ scope.row.total_amount }}
          </template>
        </el-table-column>
        <el-table-column prop="pay_amount" label="实付金额" width="120">
          <template #default="scope">
            ¥{{ scope.row.pay_amount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="下单时间" width="180"></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="handleDetail(scope.row)">详情</el-button>
            <el-button 
              v-if="scope.row.status === 'pending'"
              type="text" 
              class="delete-btn" 
              @click="handleCancel(scope.row)"
            >取消</el-button>
            <el-button 
              v-if="scope.row.status === 'paid'"
              type="text" 
              @click="handleComplete(scope.row)"
            >完成</el-button>
            <el-button 
              v-if="['paid', 'completed'].includes(scope.row.status)"
              type="text" 
              class="delete-btn"
              @click="handleRefund(scope.row)"
            >退款</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100]"
          :current-page="queryParams.page"
          :page-size="queryParams.limit"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 订单详情弹窗 -->
    <el-dialog
      title="订单详情"
      v-model="detailVisible"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ detail.order_no }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusType(detail.status)">
            {{ getStatusText(detail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="卡号">{{ detail.card_no }}</el-descriptions-item>
        <el-descriptions-item label="景区">{{ detail.scenic_spot?.name }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ detail.contact_name }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ detail.contact_phone }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">¥{{ detail.total_amount }}</el-descriptions-item>
        <el-descriptions-item label="实付金额">¥{{ detail.pay_amount }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ detail.pay_type }}</el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ detail.pay_time }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ detail.created_at }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ detail.remark }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">订单明细</el-divider>
      
      <el-table :data="detail.items" border style="width: 100%">
        <el-table-column prop="product_name" label="产品名称"></el-table-column>
        <el-table-column prop="product_type" label="产品类型" width="100">
          <template #default="scope">
            {{ typeMap[scope.row.product_type] }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="80"></el-table-column>
        <el-table-column prop="price" label="单价" width="120">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="total_amount" label="小计" width="120">
          <template #default="scope">
            ¥{{ scope.row.total_amount }}
          </template>
        </el-table-column>
        <el-table-column prop="service_date" label="服务日期" width="120"></el-table-column>
        <el-table-column prop="service_time" label="服务时间" width="120"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

export default {
  name: 'Order',
  setup() {
    // 常量
    const typeMap = {
      package: '套餐',
      single: '单品',
      service: '服务'
    }

    // 查询参数
    const queryParams = reactive({
      page: 1,
      limit: 10,
      order_no: '',
      card_no: '',
      status: '',
      dateRange: [],
      start_time: '',
      end_time: ''
    })

    // 表格数据
    const loading = ref(false)
    const orderList = ref([])
    const total = ref(0)

    // 详情数据
    const detailVisible = ref(false)
    const detail = ref({})

    // 获取订单列表
    const getList = async () => {
      loading.value = true
      try {
        // 处理时间范围
        if (queryParams.dateRange && queryParams.dateRange.length === 2) {
          queryParams.start_time = queryParams.dateRange[0]
          queryParams.end_time = queryParams.dateRange[1]
        } else {
          queryParams.start_time = ''
          queryParams.end_time = ''
        }

        const res = await request({
          url: '/app/ky_black/admin/order/list',
          method: 'get',
          params: queryParams
        })
        if (res.code === 0) {
          orderList.value = res.data.data
          total.value = res.data.total
        }
      } catch (error) {
        console.error('获取订单列表失败:', error)
      }
      loading.value = false
    }

    // 查询操作
    const handleQuery = () => {
      queryParams.page = 1
      getList()
    }

    // 重置查询
    const resetQuery = () => {
      queryParams.order_no = ''
      queryParams.card_no = ''
      queryParams.status = ''
      queryParams.dateRange = []
      handleQuery()
    }

    // 查看详情
    const handleDetail = async (row) => {
      try {
        const res = await request({
          url: '/order/detail',
          method: 'get',
          params: { order_id: row.order_id }
        })
        if (res.code === 0) {
          detail.value = res.data
          detailVisible.value = true
        }
      } catch (error) {
        console.error('获取订单详情失败:', error)
        ElMessage.error('获取订单详情失败')
      }
    }

    // 取消订单
    const handleCancel = (row) => {
      ElMessageBox.confirm('确认要取消该订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            const res = await request({
              url: '/order/cancel',
              method: 'post',
              data: { order_id: row.order_id }
            })
            if (res.code === 0) {
              ElMessage.success('订单取消成功')
              getList()
            } else {
              ElMessage.error(res.msg || '取消失败')
            }
          } catch (error) {
            console.error('取消订单失败:', error)
            ElMessage.error('取消失败')
          }
        })
        .catch(() => {})
    }

    // 完成订单
    const handleComplete = (row) => {
      ElMessageBox.confirm('确认要完成该订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            const res = await request({
              url: '/order/complete',
              method: 'post',
              data: { order_id: row.order_id }
            })
            if (res.code === 0) {
              ElMessage.success('订单已完成')
              getList()
            } else {
              ElMessage.error(res.msg || '操作失败')
            }
          } catch (error) {
            console.error('完成订单失败:', error)
            ElMessage.error('操作失败')
          }
        })
        .catch(() => {})
    }

    // 退款
    const handleRefund = (row) => {
      ElMessageBox.confirm('确认要对该订单进行退款吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            const res = await request({
              url: '/order/refund',
              method: 'post',
              data: { order_id: row.order_id }
            })
            if (res.code === 0) {
              ElMessage.success('退款成功')
              getList()
            } else {
              ElMessage.error(res.msg || '退款失败')
            }
          } catch (error) {
            console.error('退款失败:', error)
            ElMessage.error('退款失败')
          }
        })
        .catch(() => {})
    }

    // 获取状态类型
    const getStatusType = (status) => {
      const map = {
        pending: '',
        paid: 'success',
        completed: 'success',
        cancelled: 'info',
        refunded: 'warning'
      }
      return map[status] || ''
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const map = {
        pending: '待支付',
        paid: '已支付',
        completed: '已完成',
        cancelled: '已取消',
        refunded: '已退款'
      }
      return map[status] || status
    }

    // 分页操作
    const handleSizeChange = (val) => {
      queryParams.limit = val
      getList()
    }

    const handleCurrentChange = (val) => {
      queryParams.page = val
      getList()
    }

    onMounted(() => {
      getList()
    })

    return {
      typeMap,
      queryParams,
      loading,
      orderList,
      total,
      detailVisible,
      detail,
      handleQuery,
      resetQuery,
      handleDetail,
      handleCancel,
      handleComplete,
      handleRefund,
      getStatusType,
      getStatusText,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.search-wrapper {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
.delete-btn {
  color: #F56C6C;
}
</style> 